# coding=utf-8

import json
from socket import *
import threading, time
import os
import sys  
reload(sys)  
sys.setdefaultencoding('utf8')


class SendFile():
    def __init__(self, locapath, path, destination, delete, cover=False):
        #super(SendFile, self).__init__()
        self.name = path.split("/")[-1]
        self.path = path[0:-len(self.name)]
        self.delete = delete
        self.locapath = locapath
        self.ip = destination
        self.port = 13588  # 写死

        self.cover = cover


    def sendreadydata(self):
        """发送准备资源"""
        
        self.file = open(self.locapath, 'rb')
        
        self.file_data = self.file.read()

        self.len = len(self.file_data)

        self.file.close()
        
        data = {
                "path": self.path,
                "name": self.name,
                "len": self.len,
                "cover": self.cover
                }
        data = json.dumps(data)

        self.client.send(data.encode('utf-8'))
        
        recv = self.client.recv(1024)

        print "主机已就收请求: ",recv


    def generate_socket(self):       
        
        # 创建socket
        tcp_client_socket = socket(AF_INET, SOCK_STREAM)

        # 目的信息
        server_ip = self.ip
        server_port = self.port

        # 链接服务器
        tcp_client_socket.connect((server_ip, server_port))

        self.client = tcp_client_socket

    def senddata(self):
        
        self.client.send(self.file_data)
        print "文件发送完毕"
        self.client.close()

    def run(self):
        
        self.generate_socket()  # 生成套接字

        self.sendreadydata()  # 发送准备资源
        
        self.senddata()  # 发送数据
        
        if self.delete:
            print '删除文件',self.locapath
            os.system("rm %s"%(self.locapath))



    

def send_file(locapath,path,ip,delete=False,cover=False):
    """发送文件函数"""
    
    Send = SendFile(locapath, path, ip, delete=delete, cover=cover)
    Send.run()




def run(task, ip, delete=False, cover=False):
    for info in task:
        send_file(info[0], info[1], ip, delete, cover)
    

def many_file(locapath, path, ip, delete=False, cover=False, asy=False):
    """根据业务需求方便调用的语法糖"""
    if not locapath.endswith('/'):
        locapath += "/"
    if not path.endswith('/'):
        path +="/"
    
    all_name = os.listdir(locapath)

    if asy:
        if all_name:   
            task = list()
            for name in all_name:
                if os.path.isdir(locapath+name):
                    many_file(locapath+name, path+name, ip, delete=delete, cover=cover, asy=asy)
                else:
                    info = list()
                    info.append(locapath+name)
                    info.append(path+name)
                    task.append(info)

            t=threading.Thread(target=run, args=(task,ip,delete,cover))
            t.start()

            print '异步执行: ',locapath
    else:
        if all_name:   
            task = list()
            for name in all_name:
                if os.path.isdir(locapath+name):
                    many_file(locapath+name, path+name, ip, delete=delete, cover=cover, asy=asy )
                else:
                    info = list()
                    info.append(locapath+name)
                    info.append(path+name)
                    task.append(info)
            run(task, ip, delete, cover)
            print "正在发送文件夹: ", locapath
    if delete and not asy:
        os.system('rm -r %s'%locapath)
        print '清除本地文件夹'



    
    




